package com.biz.primus.ms.order.dao.specfication;

import com.biz.primus.common.utils.StringUtil;
import com.biz.primus.model.order.enums.OrderState;
import com.biz.primus.ms.order.dao.po.Order;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 * @author Tiger Feng
 * @date 2017年11月14日
 */
public class OrderSpecfication implements Specification<Order> {

    private String orderCode;

    private OrderState orderState;

    public OrderSpecfication(String orderCode, OrderState orderState) {
        this.orderCode = orderCode;
        this.orderState = orderState;
    }

    @Override
    public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = new ArrayList<>();

        if(!StringUtil.isNullOrEmpty(orderCode)){
            predicates.add(cb.like(root.get("orderCode"),"%"+orderCode+"%"));
        }
        predicates.add(cb.equal(root.get("state").as(OrderState.class),orderState));
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }
}